<script setup lang="ts">
  import {
    useGetReturnFactoryReceiptSet,
    useReturnFactoryReceiptGoodsSave,
  } from '@/services/pages/return-factory/useReturnFactory'
  import { PropType, ref, watch } from 'vue'
  import getInfoByCode from '@/services/pages/code/getInfoByCode'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const { codeInfo, getInfoLoading, getInfo } = getInfoByCode()
  const { goods, loading, save } = useReturnFactoryReceiptGoodsSave()

  defineOptions({
    name: 'SignForReceiptGoodReturnFactoryDetail',
  })

  const props = defineProps({
    returnFactoryId: {
      type: String,
      required: true,
    },
    goodList: {
      type: Array as PropType<Array<ReturnFactoryDetailGood>>,
      default: () => [],
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  interface WaitReceiptGood {
    goodName: string
    goodCode: string
    checkCode: string
    goodIndex: number
    goodsId: string
    goodsSpecId: string
    id: string
  }

  const {
    loading: getReceiptSetLoading,
    receiptSet,
    getSet: getReceiptSet,
  } = useGetReturnFactoryReceiptSet()

  // 抽屉显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 待签收设备列表
  const waitReceiptGoodList = ref<Array<WaitReceiptGood>>([])

  // 用于填充全部的校验序列号
  const allCheckCodeVal = ref('')

  // 批量填充校验序列号弹出框的显示状态
  const multipleFillInCheckCodePopoverVisible = ref(false)

  /**
   * 隐藏抽屉
   */
  const hideDrawer = () => {
    visible.value = false
  }

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    for (let i = 0; i < waitReceiptGoodList.value.length; i++) {
      const good = waitReceiptGoodList.value[i]
      if (!good.checkCode.trim() && receiptSet.value) {
        HMessageBox.error('请输入校对序列号')
        return
      }
    }
    goods.value = waitReceiptGoodList.value.map((item) => {
      return {
        id: item.id,
        goodsId: item.goodsId,
        godsSpecId: item.goodsSpecId,
        snCodeCheckResult: item.goodCode === item.checkCode ? 1 : 2,
      }
    })
    const res = await save(props.returnFactoryId)
    if (res.code === 20000) {
      HMessage.success('签收成功')
      hideDrawer()
      emits('update')
    } else {
      HMessageBox.error(res.message)
    }
  }

  /**
   * 批量填充校验序列号
   */
  const multipleFillInCheckCode = async () => {
    await getInfo(allCheckCodeVal.value)
    if (!codeInfo.value) {
      HMessageBox.error('找不到该序列号的信息')
      return
    }
    waitReceiptGoodList.value = waitReceiptGoodList.value.map((item) => {
      return {
        ...item,
        checkCode: allCheckCodeVal.value,
        goodsId: codeInfo.value.goodsId,
        goodsSpecId: codeInfo.value.goodsSpecId,
      }
    })
    multipleFillInCheckCodePopoverVisible.value = false
    allCheckCodeVal.value = ''
  }

  watch(
    visible,
    (value) => {
      if (value) {
        getReceiptSet(props.returnFactoryId)
        waitReceiptGoodList.value = props.goodList.map((item, index) => {
          return {
            goodName: item.goodsName,
            goodCode: item.code,
            checkCode: '',
            goodIndex: index,
            goodsId: '',
            goodsSpecId: '',
            id: item.id,
          }
        })
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    title="签收"
    :width="800"
    unit="px"
    :loading="getReceiptSetLoading || loading"
  >
    <el-table :border="true" stripe :data="waitReceiptGoodList">
      <!-- 序号 -->
      <el-table-column
        type="index"
        width="50"
        fixed="left"
        :align="'center'"
        label="序号"
      ></el-table-column>

      <!-- 退回设备名称 -->
      <el-table-column
        label="退回设备名称"
        prop="goodName"
        width="160"
        show-overflow-tooltip
      ></el-table-column>

      <!-- 退回设备序列号 -->
      <el-table-column
        label="退回设备序列号"
        prop="goodCode"
        min-width="200"
        show-overflow-tooltip
      ></el-table-column>

      <!-- 序列号校对 -->
      <el-table-column label="序列号校对" width="240">
        <template #header>
          <div class="check-code-table-header">
            序列号校对
            <el-popover
              v-model:visible="multipleFillInCheckCodePopoverVisible"
              trigger="click"
              width="300"
            >
              <div class="multiple-fill-check-code">
                <el-input
                  v-model.trim="allCheckCodeVal"
                  placeholder="请填写校验序列号"
                  clearable
                  @keyup.enter="multipleFillInCheckCode"
                />
                <h-button type="primary" :loading="getInfoLoading" @click="multipleFillInCheckCode"
                  >确定</h-button
                >
              </div>
              <template #reference>
                <h-plain-button :height="16" :padding-lr="4">批量</h-plain-button>
              </template>
            </el-popover>
          </div>
        </template>
        <template #default="{ row }">
          <el-input
            v-model.trim="row.checkCode"
            placeholder="请输入校对序列号"
            :disabled="!receiptSet"
          />
        </template>
      </el-table-column>

      <!-- 校对结果 -->
      <el-table-column label="校对结果" width="90">
        <template #default="{ row }">
          <template v-if="!!row.checkCode.trim()">
            {{ row.goodCode === row.checkCode ? '一致' : '不一致' }}
          </template>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <h-button type="primary" is-modal @click="onConfirm">确认签收</h-button>
      <h-button is-modal @click="hideDrawer">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .check-code-table-header {
    display: flex;
    align-items: center;
    column-gap: 5px;
  }

  .multiple-fill-check-code {
    display: flex;
    column-gap: 5px;
  }
</style>
